package com.wyq.dao.impl;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Blob;
import java.util.List;
import java.util.Map;

import com.wyq.bean.ShowInfo;
import com.wyq.dao.ShowInfoDAO;
import com.wyq.util.DateUtils;
import com.wyq.util.PropertiesUtil;
import com.wyq.util.StringUtil;
import com.wyq.util.impl.JDBCDAOSupportImpl;

public class ShowInfoDAOImpl extends JDBCDAOSupportImpl implements ShowInfoDAO {

	/**
	 * 根据ID获取展会信息
	 */
	public List getShowInfoById(String id) throws Exception {
		String sql = "select * from show_info where id = "+id ;
		List list = this.getListMapBySql(sql);
		setShowList(list);
		return list;
	}
	
	/**
	 * 根据type或urlChannel获取产会信息
	 * 
	 */
	public List getShowInfoByTypeOrUrlChannel(String type,String urlChannel) throws Exception {
		String baseSql = "select * from show_info where 1 = 1";
		String sql = baseSql;
		if(StringUtil.isNotEmpty(type)){
			sql += " and type= '"+type+"'";
		}
		
		if(StringUtil.isNotEmpty(urlChannel)){
			sql += " and urlChannel = '"+urlChannel+"'";
		}
		
		if(StringUtil.isEmpty(type) && StringUtil.isEmpty(urlChannel)){
			//主展会
			sql += " and type = '1'";
		}
		List list = this.getListMapBySql(sql);
		//当获取不到展会时，获取主展会
		if(null == list || list.size()<=0){
			baseSql += " and type = '1'";
			list = this.getListMapBySql(baseSql);
		}
		setShowList(list);
		return list;
	}
	
	/**
	 * 分页获取展会信息
	 */
	public List findPageShowInfos(String start,String limit) throws Exception {
		// TODO Auto-generated method stub
		//String sql = "select * from audiences where audience_isAvailable = 1 and type="+type+" limit " + start + "," + limit;
		String sql = "select * from show_info  order by createTime desc limit " + start + "," + limit;
		List list = this.getListMapBySql(sql);
		setShowList(list);
		//String hql = "from Audience audience where audience_isAvailable = 1 limit " + start + "," + limit;
		//List<Audience> list = this.getHibernateTemplate().find(hql);
		return list;
	}
	
	/**
	 * 获取所有的展会信息
	 * @return
	 * @throws Exception
	 */
	public List getAllShowInfo(String isAvailable) throws Exception{
		String sql = "select * from show_info where 1=1 ";
		if(StringUtil.isNotEmpty(isAvailable)){
			sql += " and isAvailable = "+isAvailable;
		}
		sql += " order by createTime desc";
		List list = this.getListMapBySql(sql);
		setShowList(list);
		//String hql = "from Audience audience where audience_isAvailable = 1 limit " + start + "," + limit;
		//List<Audience> list = this.getHibernateTemplate().find(hql);
		return list;
	}
	
	private void setShowList(List showInfos) throws Exception{
		for(int i=0;i<showInfos.size();i++){
			Map showInfo = (Map)showInfos.get(i);
			if(null != showInfo.get("remark")){
				Blob b = (Blob) showInfo.get("remark");
				if(null != b){
					InputStream is = b.getBinaryStream();				
					ByteArrayInputStream bais = (ByteArrayInputStream)is;				
					byte[] byte_data = new byte[bais.available()]; //bais.available()返回此输入流的字节数				
					bais.read(byte_data, 0,byte_data.length);//将输入流中的内容读到指定的数组				
					String remark = new String(byte_data,"utf-8"); //再转为String，并使用指定的编码方式				
					is.close();
					showInfo.put("remark",remark.toString());
					String webUrl = PropertiesUtil.getVal("weburl") + ((showInfo.get("urlChannel")!=null && !"".equals(showInfo.get("urlChannel").toString()))?("?source="+showInfo.get("urlChannel").toString()):"");
					//设置展会链接
					showInfo.put("webUrl", webUrl);
					showInfos.set(i, showInfo);
				}
				/*InputStream is = b.getBinaryStream();
				BufferedReader reader = new BufferedReader(new InputStreamReader(is));   
				StringBuffer remark = new StringBuffer();
				String line = null; 
				while ((line = reader.readLine()) != null) {   
					remark.append(line + "/n");   
		        }    
				is.close();*/
			}
		}
	}

	/**
	 * 新增展会信息
	 */
	public int insertShowInfo(ShowInfo showInfo) throws Exception {
		String sql = "";
		sql = "insert into show_info(id,showName,showCompany,showTime,showAddress,"
				+"showTel,showFax,showEmail,showContact,type,urlChannel,createTime,"
				+"isAvailable) values("
				+ "(select max(id)+1 from show_info)"
				+ ",'" + showInfo.getShowName() + "'"
				+ ",'" + showInfo.getShowCompany() + "'"
				+ ",'" + showInfo.getShowTime() + "'"
				+ ",'" + showInfo.getShowAddress() + "'"
				+ ",'" + showInfo.getShowTel() + "'"
				+ ",'" + showInfo.getShowFax() + "'"
				+ ",'" + showInfo.getShowEmail() + "'"
				+ ",'" + showInfo.getShowContact() + "'"
				+ ",'" + showInfo.getType() + "'"
				+ ",'" + showInfo.getUrlChannel() + "'"
				+ ",'"+DateUtils.getCurrentDateStr("yyyy-MM-dd HH:mm:ss")+"'"
				+ ",1)"; 
		int flag = this.execupdateBySql(sql);
		return 0;
	}
	
	/**
	 * 修改展会信息
	 */
	public int updateShowInfo(Map showInfo) throws Exception {
		String type = showInfo.get("type")!=null?showInfo.get("type").toString():"";//展会类型
		List<ShowInfo> list = null;
		if(null != showInfo.get("id") && !"".equals(showInfo.get("id"))){
			list = this.getShowInfoById(showInfo.get("id").toString());
		}
		//判断是否已添加主展会且修改的不是主展会的信息
		List<ShowInfo> mainShowInfos = this.getShowInfoByTypeOrUrlChannel(null, null);
		if(null != mainShowInfos && mainShowInfos.size()>0){
			Map domain = (Map)mainShowInfos.get(0);
			if("1".equals(type) && !(showInfo.get("id").toString()).equals(domain.get("id").toString())){
				return -1;
			}
		}
		//主展会不设置参数
		if("1".equals(type)){
			showInfo.put("urlChannel", "");
		}
		
		String sql = "";
		if(null == list || list.size() <= 0){
			String showInfoId = "1";
			String maxSql = "select max(id)+1 as maxid from show_info" ;
			List<Map> maxList = this.getListMapBySql(maxSql);
			if(null != maxList && maxList.size()>0){
				showInfoId = maxList.get(0).get("maxid").toString();
			}
			
			sql = "insert into show_info(id,showName,showCompany,showTime,showAddress,"
					+"showTel,showFax,showEmail,showContact,type,urlChannel,createTime,"
					+"hearderImgPath,remark,isAvailable) values("
				+ showInfoId
				+ ",'" + showInfo.get("showName").toString() + "'"
				+ ",'" + showInfo.get("showCompany").toString() + "'"
				+ ",'" + showInfo.get("showTime").toString() + "'"
				+ ",'" + showInfo.get("showAddress").toString() + "'"
				+ ",'" + showInfo.get("showTel").toString() + "'"
				+ ",'" + showInfo.get("showFax").toString() + "'"
				+ ",'" + showInfo.get("showEmail").toString() + "'"
				+ ",'" + showInfo.get("showContact").toString() + "'"
				+ ",'" + showInfo.get("type").toString() + "'"
				+ ",'" + (showInfo.get("urlChannel")!=null?showInfo.get("urlChannel").toString():"") + "'"
				+ ",'" + DateUtils.getCurrentDateStr("yyyy-MM-dd HH:mm:ss")+"'"
				+ ",'"+(showInfo.get("hearderImgPath")!=null?showInfo.get("hearderImgPath").toString():"")+"'"
				+ ",'"+showInfo.get("remark").toString()+"'"
				+ ",1)"; 
		}else{
			Map showMap = (Map)list.get(0);
			sql = "update show_info set showName = '" + showInfo.get("showName").toString()
				+ "',showCompany = '" + showInfo.get("showCompany").toString()
				+ "',showTime = '" + showInfo.get("showTime").toString()
				+ "',showAddress = '" + showInfo.get("showAddress").toString()
				+ "',showTel = '" + showInfo.get("showTel").toString()
				+ "',showFax = '" + showInfo.get("showFax").toString()
				+ "',showEmail = '" + showInfo.get("showEmail").toString()
				+ "',isAvailable = " + showInfo.get("isAvailable").toString()
				+ ",showContact='" + showInfo.get("showContact").toString() + "'"
				+ ",type='" + showInfo.get("type").toString() + "'"
				+ ",urlChannel='" + (showInfo.get("urlChannel")!=null?showInfo.get("urlChannel").toString():"") + "'"
				//+ ",createTime='"+DateUtils.getCurrentDateStr("yyyy-MM-dd HH:mm:ss")+"'"
				+ ",hearderImgPath='"+(showInfo.get("hearderImgPath")!=null?showInfo.get("hearderImgPath").toString():"")+"'"
				+ ",remark='"+showInfo.get("remark").toString()+"'"
				+ " where id = " + showMap.get("id").toString();
				;
		}
		if(!"".equals(sql)){
			this.execupdateBySql(sql);
		}
		return 1;
	}
	
	/**
	 * 删除展会
	 * @param id
	 * @return
	 * @throws Exception
	 */
	public int deleteById(String id) throws Exception{
		String sql = "";
		if(null != id && !"".equals(id)){
			sql += "delete from show_info where id = "+id;
			this.execupdateBySql(sql);
			return 1;
		}else{
			return -1;
		}
		
	}

}
